package com.iot.manager.ui.activities;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.button.MaterialButton;
import com.iot.manager.R;
import com.iot.manager.data.models.DeviceData;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.ui.fragments.DeviceDataFragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HistoryActivity extends AppCompatActivity {

    private static final String TAG = "HistoryActivity";
    private static final int ITEMS_PER_PAGE = 15;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    private Toolbar toolbar;
    private ProgressBar progressBar;
    private View errorLayout;
    private TextView errorText;
    private MaterialButton btnPrevPage;
    private MaterialButton btnNextPage;
    private MaterialButton btnDateRange;
    private String deviceId;
    private Date startDate;
    private Date endDate;
    private List<DeviceData> filteredDataList = new ArrayList<>();
    private int currentPage = 1;
    private int totalPages = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        // 获取设备ID
        deviceId = getIntent().getStringExtra("device_id");
        if (deviceId == null || deviceId.isEmpty()) {
            Toast.makeText(this, "设备ID不能为空", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化日期范围
        endDate = new Date();
        startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000L); // 默认显示最近7天

        // 初始化视图
        initViews();
        setupToolbar();
        setupDateRangePicker();
        setupFragments();
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        progressBar = findViewById(R.id.progressBar);
        errorLayout = findViewById(R.id.errorLayout);
        errorText = findViewById(R.id.errorText);
        btnPrevPage = findViewById(R.id.btnPrevPage);
        btnNextPage = findViewById(R.id.btnNextPage);
        btnDateRange = findViewById(R.id.btnDateRange);
    }

    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("历史数据");
        }
    }

    private void setupDateRangePicker() {
        MaterialDatePicker<androidx.core.util.Pair<Long, Long>> dateRangePicker = MaterialDatePicker.Builder.dateRangePicker()
                .setTitleText("选择日期范围")
                .setSelection(androidx.core.util.Pair.create(startDate.getTime(), endDate.getTime()))
                .build();

        btnDateRange.setOnClickListener(v -> dateRangePicker.show(getSupportFragmentManager(), "DATE_RANGE_PICKER"));

        dateRangePicker.addOnPositiveButtonClickListener(selection -> {
            startDate = new Date(selection.first);
            endDate = new Date(selection.second);
            updateDateRangeButton();
            loadData();
        });
    }

    private void updateDateRangeButton() {
        String dateRange = String.format("%s 至 %s",
                DATE_FORMAT.format(startDate),
                DATE_FORMAT.format(endDate));
        btnDateRange.setText(dateRange);
    }

    private void setupFragments() {
        // 创建数据页面
        DeviceDataFragment dataFragment = DeviceDataFragment.newInstance(deviceId);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer, dataFragment)
                .commit();
    }

    private void loadData() {
        // 显示加载进度
        showLoading();

        // 调用API
        RetrofitClient.getInstance()
                .getApiService()
                .getDeviceData(deviceId, startDate, endDate)
                .enqueue(new Callback<List<DeviceData>>() {
                    @Override
                    public void onResponse(Call<List<DeviceData>> call, Response<List<DeviceData>> response) {
                        hideLoading();
                        if (response.isSuccessful() && response.body() != null) {
                            filteredDataList = response.body();
                            totalPages = (int) Math.ceil((double) filteredDataList.size() / ITEMS_PER_PAGE);
                            currentPage = 1;
                            updateUI();
                        } else {
                            showError("加载数据失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<List<DeviceData>> call, Throwable t) {
                        hideLoading();
                        showError("网络请求失败: " + t.getMessage());
                    }
                });
    }

    private void updateUI() {
        // 计算当前页的数据范围
        int startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
        int endIndex = Math.min(startIndex + ITEMS_PER_PAGE, filteredDataList.size());
        List<DeviceData> pageData = filteredDataList.subList(startIndex, endIndex);

        // 更新适配器数据
        DeviceDataFragment fragment = (DeviceDataFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragmentContainer);
        if (fragment != null) {
            fragment.updateData(pageData);
        }

        // 显示/隐藏空数据提示
        if (filteredDataList.isEmpty()) {
            showError("暂无数据");
        } else {
            hideError();
        }
    }

    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        errorLayout.setVisibility(View.GONE);
    }

    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
    }

    private void showError(String message) {
        errorText.setText(message);
        errorLayout.setVisibility(View.VISIBLE);
    }

    private void hideError() {
        errorLayout.setVisibility(View.GONE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 